<?php

class AuthController extends Controller_Action
{
    /**
     * @var Model\Users
     */
    private $mUsers     = NULL;
    /**
     * @var Model\Auth\filterInput
     */
    private $mFInput    = NULL;
    /**
     * @var Model\channels
     */
    private $mChannels  = NULL;
    
    public function init()
    {
        parent::init();
        
        // i18n
        \Helper\loadI18n('auth', 'main');
        \Helper\loadI18n('auth', 'errors');
        
        // models
        $this->mUsers    = new Model\Users();
        
        \Helper\loadModel('auth', 'filterInput');
        $this->mFInput  = new Model\Auth\filterInput();
        
        \Helper\loadModel('channels', 'channels');
        $this->mChannels = new Model\channels();
    }

    public function indexAction()
    {   
        $this->_helper->redirector('login');
    }
    
    public function loginAction($msg = NULL)
    {
        if ($this->getPost('submitRegister')) :
            $this->_helper->redirector('register');
        elseif ( ! $this->getPost('submitLogin')) :
            $this->createCSRFToken();
            switch ($msg)
            {
                case 'successfulActivation':
                {
                    $this->view->sucFormHead =
                        array(\ZReg::get('i18n')->get('successfulActivation'));
                }
                break;
                case 'errSessionExists':
                {
                    $this->view->errFormHead =
                        array(\ZReg::get('i18n')->get('errSessionExists'));
                }
                break;
                case 'successfulLogout':
                {
                    $this->view->sucFormHead =
                        array(\ZReg::get('i18n')->get('successfulLogout'));
                }
                break;
            }
            return;
        endif;
        // try to login
        // check input
        $filtInp = $this->mFInput->login();
        if ( ! $this->filterInput(  $filtInp->filters,
                                    $filtInp->validators,
                                    $_POST, FALSE)) return;
        // check and process, if no error then login (create session, token...)
        $ctrlLogin = $this->mUsers->ctrlLoginUser($this->inPost);
        if (($this->view->errFormHead = $ctrlLogin['err'])) return;
        
        // redirect to the events controller (home)
        $this->_helper->getHelper('Redirector')->
            gotoUrl('/events');
    }
    
    public function registerAction()
    {                
        if ( ! $this->getPost('submitRegister')) :
            $this->createCSRFToken();
            return;
        endif;    
        // check input
        $filtInp = $this->mFInput->register();
        if ( ! $this->filterInput(  $filtInp->filters,
                                    $filtInp->validators,
                                    $_POST, FALSE)) return;
        // check and process
        $ctrlInsert = $this->mUsers->ctrlInsertUser($this->inPost);
        if (($this->view->errFormHead = $ctrlInsert['err'])) return;
        
        $userId = $ctrlInsert['ret'];
        
        $this->mChannels->insertChannelDefault($userId);
        // send activation email
        $result =
        $this->mUsers->ctrlSendRegistrationEmail(
            $userId,
            array(  'email' => $this->inPost['email'],
                    'name'  => $this->inPost['name']));
        if ($result)
        {
            $this->view->sucFormHead =
                array(\ZReg::get('i18n')->get('successfulProcessing'));
            $this->view->infFormHead =
                array(\ZReg::get('i18n')->get('checkMail'));
        }
        else
            $this->view->errFormHead =
                array(\ZReg::get('i18n')->get('unsuccessfulProcessing'));
    }
    
    public function activateRegistrationAction($id, $code)
    {
        $this->_helper->viewRenderer->setNoRender();
        
        $userId = (int)base64_decode($id);
        // error handling
        if ( ! $userId)
            throw new InvalidArgumentException('$id is not an int!');
        elseif (strlen($code) !== 40)
            throw new LengthException('$code length is not 40!');
        // everything is ok
        $this->mUsers->ctrlActivateUser($userId, $code);
        // if here, that means no exception
        // so success activation -> redirect to login page
        $this->_helper->getHelper('Redirector')->
            gotoUrl('/auth/login/msg/successfulActivation');
    }
    
    public function logoutAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        
        try
        {
            $this->mUsers->ctrlLogoutUser();
            
            $this->_helper->getHelper('Redirector')->
                gotoUrl('/auth/login/msg/successfulLogout');
        }
        catch (DomainException $e)
        {
            $this->_helper->getHelper('Redirector')->
                gotoUrl('/auth/login/msg/errSessionExists');
        }
    }
}